import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
const DB = require('../../../app/db');
import Utils from './../../../utils'
import update from 'react-addons-update';
import StorageUtils from './../../../app/storage'
import nattyStorage from 'natty-storage';

const storageEngs = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-dingtalk-engs',     // !!! 唯一必选的参数, 用于内部存储 !!!
});

export default Reflux.createStore({
    listenables: [Actions],
    data: {
        ...PageConst,
      lastPage: false,
      keyword: '',
      currentPage: 1,
      pageSize: 5,
      jdfzr: '',
      engls:[],
      userInfo: {
        certNum: '',
        telNum: '',
        vcode: '',
        name:'',
        organName:''
      },
    },

    onFetch: function (params, cb) {
        let t = this;
        t.updateComponent();
        cb && cb(t.data);
    },

  onEngInit: function () {
    let t = this;
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getStorage().get('user')}});
    //第一次进入在reflux的状态中无数据才从浏览器缓存中读取
    if (t.data.engls.length == 0) {
      this.onEngFetch({
        page: 1,
        jdfzr:'',
        size: 5,
      });
    }
    t.updateComponent();
  },


  onEngFetch: function (params) {

    let t = this;
    console.log('engfetch');
    params.page = t.data.currentPage;
    params.size = t.data.pageSize;
    params.jdfzr = this.data.userInfo.telNum;
    console.info('用户数据：');
    console.info(this.data.userInfo);
    DB.WechatAPI.getEng(params).then(
      function (content) {
        if (content.length <= 0) {
          console.info('未查找到数据');
        }
        else
        {
          console.info('数据：');
          console.info(content);

          t.data.engls = update(t.data.engls, {$set: content});
          console.info('转换数据2：');
          console.info(t.data.engls);
        }
          //如果请求后数据数量小于pageSize则设置为最后一页
        t.data.lastPage = true;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
      });
  },

  updateComponent: function () {
        this.trigger(this.data);
  },

  getDefaultProps: function () {
    console.log('getDefaultProps');
    this.onEngFetch({
      page: 1,
      downOrUp: 'down',
    });
  },

  getInitialState: function () {
    console.log('getInitialState');
        return this.data;
  }
});
